<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="C++,Windows环境编程,">





  <link rel="alternate" href="/atom.xml" title="恋恋风辰的个人博客" type="application/atom+xml">






<meta name="description" content="linux 环境有提供好的pthread_cond_wait() 和 phread_signal()、pthread_broadcast()windows需要自己封装，利用semophore控制线程等待和释放，先简单谈一下设计好后api该如何使用。假设我们封装好条件变量等待函数名字叫做wait(Mutex&amp;amp; mutex)，Mutex是之前我们封装的条件变量，文章最下边会给出这些文件的下载地">
<meta name="keywords" content="C++,Windows环境编程">
<meta property="og:type" content="article">
<meta property="og:title" content="windows环境下封装条件wait和signal">
<meta property="og:url" content="http://www.limerence2017.com/2017/08/03/winsignal/index.html">
<meta property="og:site_name" content="恋恋风辰的个人博客">
<meta property="og:description" content="linux 环境有提供好的pthread_cond_wait() 和 phread_signal()、pthread_broadcast()windows需要自己封装，利用semophore控制线程等待和释放，先简单谈一下设计好后api该如何使用。假设我们封装好条件变量等待函数名字叫做wait(Mutex&amp;amp; mutex)，Mutex是之前我们封装的条件变量，文章最下边会给出这些文件的下载地">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/03/winsignal/winsignal/1.png">
<meta property="og:image" content="http://www.limerence2017.com/2017/08/03/winsignal/winsignal/2.png">
<meta property="og:updated_time" content="2020-06-22T09:30:59.121Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="windows环境下封装条件wait和signal">
<meta name="twitter:description" content="linux 环境有提供好的pthread_cond_wait() 和 phread_signal()、pthread_broadcast()windows需要自己封装，利用semophore控制线程等待和释放，先简单谈一下设计好后api该如何使用。假设我们封装好条件变量等待函数名字叫做wait(Mutex&amp;amp; mutex)，Mutex是之前我们封装的条件变量，文章最下边会给出这些文件的下载地">
<meta name="twitter:image" content="http://www.limerence2017.com/2017/08/03/winsignal/winsignal/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.limerence2017.com/2017/08/03/winsignal/">





  <title>windows环境下封装条件wait和signal | 恋恋风辰的个人博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">恋恋风辰的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.limerence2017.com/2017/08/03/winsignal/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="恋恋风辰">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="恋恋风辰的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">windows环境下封装条件wait和signal</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-08-03T17:46:34+08:00">
                2017-08-03
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/netprogram/" itemprop="url" rel="index">
                    <span itemprop="name">网络编程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>linux 环境有提供好的<code>pthread_cond_wait()</code> 和 <code>phread_signal()</code>、<code>pthread_broadcast()</code>windows需要自己封装，利用<code>semophore</code>控制线程等待和释放，先简单谈一下设计好后api该如何使用。假设我们封装好条件变量等待函数名字叫做<code>wait(Mutex&amp; mutex)</code>，Mutex是之前我们封装的条件变量，文章最下边会给出这些文件的下载地址，在这里读者当做linux 的mutex即可。我们封装的释放函数为<code>signal()</code>,广播函数为<code>broadcast</code>。<br><a id="more"></a><br>判断等待条件变量和逻辑处理如下：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">Lock(mutex);</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span>(条件不满足)</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line"> 　  wait(mutex);</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">todo...;</span><br><span class="line"></span><br><span class="line">UnLock(mutex);</span><br></pre></td></tr></table></figure></p>
<p>激活条件变量如下：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">Lock(mutex);</span><br><span class="line"></span><br><span class="line">　　todo ...;　</span><br><span class="line"></span><br><span class="line">　　<span class="keyword">if</span>(条件满足)</span><br><span class="line"></span><br><span class="line">　　&#123;</span><br><span class="line"></span><br><span class="line">　　　　signal();/broadcast();</span><br><span class="line"></span><br><span class="line">　　&#125;　</span><br><span class="line"></span><br><span class="line">signal();</span><br><span class="line"></span><br><span class="line">UnLock(mutex);</span><br></pre></td></tr></table></figure></p>
<p>Condition 是我们封装的条件变量类这是封装好api后调用规则，那么先考虑wait内部的基本形式<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> Condition::wait(Mutex &amp;mutex)</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line">　　<span class="comment">//1 Condition 类中表示阻塞线程数　</span></span><br><span class="line"></span><br><span class="line">　　mblocked ++;</span><br><span class="line"></span><br><span class="line">　　<span class="comment">//2 解锁，释放互斥量</span></span><br><span class="line"></span><br><span class="line">　　UnLock(mutex);</span><br><span class="line"></span><br><span class="line">　　<span class="comment">//3 阻塞等待 mQueue为信号量</span></span><br><span class="line"></span><br><span class="line">　  res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mQueue), INFINITE);</span><br><span class="line"></span><br><span class="line">　  <span class="comment">//4 做一些判断和逻辑处理</span></span><br><span class="line"></span><br><span class="line">　　<span class="comment">//5　加锁</span></span><br><span class="line"></span><br><span class="line"> 　Lock(mutex);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>wait内部记录一个阻塞的线程数mblocked，mblocked 是我们封装Condition类的成员变量，<br>然后释放外部的互斥量，然后调用阻塞函数，等待signal唤醒。<br>当WaitForSingleObject获取信号后会继续执行，做一些逻辑判断，最后将mutex锁住。<br>这里用到的mQueue是一个信号量，用信号量可以接受多个唤醒和控制线程唤醒数量。<br>下面是条件变量释放的函数，我们先做只是放一个条件变量的api<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> Condition::signal()</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line">　　<span class="comment">//1阻塞的线程减少</span></span><br><span class="line"></span><br><span class="line">　　mblocked --;</span><br><span class="line"></span><br><span class="line">　　<span class="comment">//2将激活的信号个数设置为1</span></span><br><span class="line"></span><br><span class="line">　　signals = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">　　<span class="comment">//3</span></span><br><span class="line"></span><br><span class="line">　　<span class="keyword">if</span> (signals)</span><br><span class="line"></span><br><span class="line">　　&#123;</span><br><span class="line"></span><br><span class="line">　　　　<span class="comment">//释放信号量</span></span><br><span class="line">　　　　res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mQueue), signals, <span class="number">0</span>);</span><br><span class="line">　　　　ASSERT(res);</span><br><span class="line">　　&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>先不要着急往下写，考虑下这么做真的合适么？<br>首先之前设计过外部调用<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(条件满足)</span><br><span class="line"></span><br><span class="line">　　&#123;</span><br><span class="line"></span><br><span class="line">　　　　signal();/broadcast();</span><br><span class="line"></span><br><span class="line">　　&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个只要条件满足就可以激活，所以我们只用mblocked表示阻塞线程数是不够的，当信号量被激活很多没有被消耗的情况下就需要统计当前可用的资源数，那么就在Condition类添加mWait表示当前可用的信号量个数。除此之外，考虑这样一种情况，当条件不满足的时候 线程A调用void wait(Mutex &amp;mutex)函数，wait函数先解锁再阻塞，对应wait中第2,3步骤。而另一个线程B当条件满足时调用 signal函数激活之前阻塞的线程A，对应signal函数中第3步。原阻塞线程A因为捕获到信号量，所以一次走到wait中第4、5步。由于第4和第5步之间没有加锁保护，所以这一阶段用到的类的成员变量都是不安全的。所以在第3和第4之间加一个互斥锁，第5步之后释放这个互斥锁。同样的道理，为了避免此时signal内部调用类的成员变量造成数据不一致所以signal内部也需要加锁，在signal内部第1步之前加锁，第3步之后解锁，或者第3步之前解锁都可以。我觉得在第三步之前释放会好一些，在释放信号量之前解锁，避免死锁。所以添加一个成员变量mMutex用于部分代码互斥。<br>那么改良后我们的函数如下：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span></span><br><span class="line">Condition::wait(Mutex&amp; mutex)</span><br><span class="line">&#123;</span><br><span class="line">　　<span class="meta">#<span class="meta-keyword">ifndef</span> WIN32</span></span><br><span class="line">    　　<span class="keyword">int</span> ret = pthread_cond_wait(&amp;mId, mutex.getId());</span><br><span class="line">    　　ASSERT(ret == <span class="number">0</span>);</span><br><span class="line">　　<span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line">    <span class="comment">//1</span></span><br><span class="line">    mBlocked++;&lt;br&gt;        <span class="comment">//2</span></span><br><span class="line">    　　mutex.unlock();</span><br><span class="line"> </span><br><span class="line">    　　<span class="keyword">int</span> res = <span class="number">0</span>;&lt;br&gt;　　　　 <span class="comment">//3</span></span><br><span class="line">   　　 res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mQueue), INFINITE);</span><br><span class="line">    　　ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">     </span><br><span class="line">    <span class="comment">//用于暂时存储mWaiting的数值</span></span><br><span class="line">   　　  <span class="keyword">unsigned</span> wasWaiting = <span class="number">0</span>;</span><br><span class="line">   　　 <span class="comment">//4</span></span><br><span class="line">    　　res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex), INFINITE);</span><br><span class="line">    　　ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">    　　wasWaiting = mWaiting;</span><br><span class="line">   　　 <span class="comment">//5</span></span><br><span class="line">   　　 res = ReleaseMutex(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex));</span><br><span class="line">    　　ASSERT(res);</span><br><span class="line">　　　　<span class="comment">//6</span></span><br><span class="line">  　　　mutex.lock();</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>步骤也做了相应的调整。<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span></span><br><span class="line">Condition::signal ()</span><br><span class="line">&#123;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> WIN32</span></span><br><span class="line">    <span class="keyword">int</span> ret = pthread_cond_signal(&amp;mId);</span><br><span class="line">    ASSERT(ret == <span class="number">0</span>);</span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line">    <span class="keyword">unsigned</span> signals = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> res = <span class="number">0</span>;</span><br><span class="line">　　<span class="comment">//1</span></span><br><span class="line">    res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex), INFINITE);</span><br><span class="line">    ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">　　<span class="comment">//2</span></span><br><span class="line">    <span class="keyword">if</span> (mWaiting != <span class="number">0</span>) </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> (mBlocked == <span class="number">0</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            res = ReleaseMutex(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex));</span><br><span class="line">            ASSERT(res);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        ++mWaiting;</span><br><span class="line">        --mBlocked;</span><br><span class="line">        signals = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        signals = mWaiting = <span class="number">1</span>;</span><br><span class="line">        --mBlocked;</span><br><span class="line">            </span><br><span class="line">    &#125;</span><br><span class="line">　　<span class="comment">//3</span></span><br><span class="line">    res = ReleaseMutex(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex));</span><br><span class="line">    ASSERT(res);</span><br><span class="line">　　<span class="comment">//4</span></span><br><span class="line">    <span class="keyword">if</span> (signals)</span><br><span class="line">    &#123;</span><br><span class="line">        res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mQueue), signals, <span class="number">0</span>);</span><br><span class="line">        ASSERT(res);</span><br><span class="line">    &#125;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>改良后更新了步骤，注释的就是步骤，方便接下来讨论这两段代码的隐患，因为仅仅这些还不够。目前现总结下mMutex作用：</p>
<p><code>1 mMutex用于signal函数内部和wait函数 获取信号量之后的代码互斥，保护类的常用变量。</code>  </p>
<p><code>2 当不同的线程调用wait等待后获得激活时，mMutex保证获得信号量之后的操作是互斥的，安全的。</code>  </p>
<p>由于调用wait函数之前需要加外部的互斥锁，所以不同的线程调用wai函数时第一步的mBlocked++是互斥的，不会出错。  </p>
<p>唯一有可能出错的是那种情况呢？  </p>
<p>就是当signal发出信号后，当前有一个因为调用wait阻塞的线程A捕获到该信号，进入第四步，修改或者访问mBlocked变量的值，与此同时有线程A调用wait函数，此时会进入wait内部第一步mBlocked++，多线程修改和读取mBlocked会造成数据混乱，所以此时需要在第一步之前加锁，第2步之前解锁，因此添加单个信号量mGate，用于控制当有线程处于解锁状态处理mBlocked等类成员时，其他线程进入wait修改mBlocked值。<br>这个res = WaitForSingleObject(reinterpret_cast<handle>(mGate), INFINITE);可以放在wait函数第4步之后，当第4步获得互斥资源后，阻塞等待获取mGate信号，如果没获得需要等待别的线程释放mGate，如果此时mGate不被释放造成mMutex死锁。所以别的线程中先调用 WaitForSingleObject(reinterpret_cast<handle>(mGate), INFINITE);后调用WaitForSingleObject mMutex会造成死锁。需要特别注意。如果规避了这一点，那么就可以避免死锁。所有情况都对mGate互斥访问并不友好，出现之前讨论的情况只有一种：就是当前应用程序中至少有一个线程处于等待，而signal释放信号后，某一个等待的线程继续执行4后面的操作，外界有新的线程调用wait时修改mBlocked会出错。所以只需要在signal函数中判断当mWaiting数量为0时对mGate加锁，mWait根据不同情况进行对mGate进行释放。<br>修改后的代码如下：  </handle></handle></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span></span><br><span class="line">Condition::enterWait ()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">int</span> res = <span class="number">0</span>;</span><br><span class="line">    res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), INFINITE);</span><br><span class="line">    ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">    ++mBlocked;</span><br><span class="line">    res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), <span class="number">1</span>, <span class="number">0</span>);</span><br><span class="line">    ASSERT(res);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对mBlocked起到保护作用<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span></span><br><span class="line">Condition::wait(Mutex&amp; mutex)</span><br><span class="line">&#123;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> WIN32</span></span><br><span class="line">    <span class="keyword">int</span> ret = pthread_cond_wait(&amp;mId, mutex.getId());</span><br><span class="line">    ASSERT(ret == <span class="number">0</span>);</span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line">    <span class="comment">//1</span></span><br><span class="line">　　enterWait();</span><br><span class="line">　　<span class="comment">//2</span></span><br><span class="line">    mutex.unlock();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> res = <span class="number">0</span>;</span><br><span class="line">　　<span class="comment">//3</span></span><br><span class="line">    res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mQueue), INFINITE);</span><br><span class="line">    ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">unsigned</span> wasWaiting = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">unsigned</span> wasGone = <span class="number">0</span>;</span><br><span class="line">　　<span class="comment">//4</span></span><br><span class="line">    res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex), INFINITE);</span><br><span class="line">    ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">    wasWaiting = mWaiting;</span><br><span class="line">    wasGone = mGone;</span><br><span class="line">　　<span class="comment">//signal释放资源后，mWaiting 至少为1</span></span><br><span class="line">    <span class="keyword">if</span> (wasWaiting != <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">　　　　<span class="comment">//判断mWaiting 数量为1</span></span><br><span class="line">        <span class="keyword">if</span> (--mWaiting == <span class="number">0</span>)</span><br><span class="line">        &#123;</span><br><span class="line">　　　　　　　<span class="comment">//如果当前没有阻塞线程则释放mGate</span></span><br><span class="line">            <span class="keyword">if</span> (mBlocked != <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), <span class="number">1</span>, <span class="number">0</span>); <span class="comment">// open mGate</span></span><br><span class="line">                ASSERT(res);</span><br><span class="line">                wasWaiting = <span class="number">0</span>;</span><br><span class="line">            &#125;</span><br><span class="line">           </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">   <span class="comment">//5</span></span><br><span class="line">    res = ReleaseMutex(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex));</span><br><span class="line">    ASSERT(res);</span><br><span class="line">　　<span class="comment">//6</span></span><br><span class="line">    mutex.lock();</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>对应的signal函数：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span></span><br><span class="line">Condition::signal ()</span><br><span class="line">&#123;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> WIN32</span></span><br><span class="line">    <span class="keyword">int</span> ret = pthread_cond_signal(&amp;mId);</span><br><span class="line">    ASSERT(ret == <span class="number">0</span>);</span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line">    <span class="keyword">unsigned</span> signals = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> res = <span class="number">0</span>;</span><br><span class="line">　　<span class="comment">//1</span></span><br><span class="line">    res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex), INFINITE);</span><br><span class="line">    ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">　　</span><br><span class="line">    <span class="keyword">if</span> (mWaiting != <span class="number">0</span>) </span><br><span class="line">    &#123;</span><br><span class="line">　　　　<span class="comment">//当前有空闲的信号量并且没由阻塞的线程</span></span><br><span class="line">        <span class="keyword">if</span> (mBlocked == <span class="number">0</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            res = ReleaseMutex(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex));</span><br><span class="line">            ASSERT(res);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">　　　　<span class="comment">//如果由阻塞的线程，那么阻塞数量--</span></span><br><span class="line">        ++mWaiting;</span><br><span class="line">        --mBlocked;</span><br><span class="line">        signals = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">       <span class="comment">//2当空闲的信号量为0时，互斥获得mGate</span></span><br><span class="line">　　　　 res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), INFINITE);</span><br><span class="line">        ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">　　　　 <span class="comment">//3</span></span><br><span class="line">        <span class="keyword">if</span> (mBlocked )</span><br><span class="line">        &#123;</span><br><span class="line">          　<span class="comment">//如果当前有线程阻塞那么更新计数</span></span><br><span class="line">            signals = mWaiting = <span class="number">1</span>;</span><br><span class="line">            --mBlocked;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">　　　　　　 <span class="comment">//由于用户外部不判断条件是否成立多次调动signal，此处不处理直接释放mGate</span></span><br><span class="line">            res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), <span class="number">1</span>, <span class="number">0</span>);</span><br><span class="line">            ASSERT(res);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">　　<span class="comment">//4</span></span><br><span class="line">    res = ReleaseMutex(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex));</span><br><span class="line">    ASSERT(res);</span><br><span class="line"></span><br><span class="line">　　<span class="comment">//5</span></span><br><span class="line">    <span class="keyword">if</span> (signals)</span><br><span class="line">    &#123;</span><br><span class="line">        res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mQueue), signals, <span class="number">0</span>);</span><br><span class="line">        ASSERT(res);</span><br><span class="line">    &#125;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>到目前为止，对于共享对象的保护和同步都做的比较完善了，还要注意一个问题就是虚假唤醒。这是操作系统可能出现的一种情况，所以需要添加虚假唤醒的逻辑用mGone成员变量表示出错的或是虚假唤醒的线程数<br>最终代码如下：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span></span><br><span class="line">Condition::wait(Mutex&amp; mutex)</span><br><span class="line">&#123;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> WIN32</span></span><br><span class="line">    <span class="keyword">int</span> ret = pthread_cond_wait(&amp;mId, mutex.getId());</span><br><span class="line">    ASSERT(ret == <span class="number">0</span>);</span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line">    enterWait();</span><br><span class="line"></span><br><span class="line">    mutex.unlock();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> res = <span class="number">0</span>;</span><br><span class="line">    res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mQueue), INFINITE);</span><br><span class="line">    ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">unsigned</span> wasWaiting = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">unsigned</span> wasGone = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex), INFINITE);</span><br><span class="line">    ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">    wasWaiting = mWaiting;</span><br><span class="line">    wasGone = mGone;</span><br><span class="line">    <span class="keyword">if</span> (wasWaiting != <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> (--mWaiting == <span class="number">0</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span> (mBlocked != <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), <span class="number">1</span>, <span class="number">0</span>); <span class="comment">// open mGate</span></span><br><span class="line">                ASSERT(res);</span><br><span class="line">                wasWaiting = <span class="number">0</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (mGone != <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                mGone = <span class="number">0</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (++mGone == (ULONG_MAX / <span class="number">2</span>))</span><br><span class="line">    &#123;</span><br><span class="line">        res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), INFINITE);</span><br><span class="line">        ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">        mBlocked -= mGone;</span><br><span class="line">        res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), <span class="number">1</span>, <span class="number">0</span>);</span><br><span class="line">        ASSERT(res);</span><br><span class="line">        mGone = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    res = ReleaseMutex(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex));</span><br><span class="line">    ASSERT(res);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (wasWaiting == <span class="number">1</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">for</span> (; wasGone; --wasGone)</span><br><span class="line">        &#123;</span><br><span class="line">            res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mQueue), INFINITE);</span><br><span class="line">            ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">        &#125;</span><br><span class="line">        res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), <span class="number">1</span>, <span class="number">0</span>);</span><br><span class="line">        ASSERT(res);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    mutex.lock();</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>wait部分添加了mGone的处理，当mWaiting数量为0进入<br>res = WaitForSingleObject(reinterpret_cast<handle>(mMutex), INFINITE);<br>需要对mGone++表示虚假唤醒的线程数量<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (++mGone == (ULONG_MAX / <span class="number">2</span>))</span><br><span class="line">    &#123;</span><br><span class="line">        res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), INFINITE);</span><br><span class="line">        ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">        mBlocked -= mGone;</span><br><span class="line">        res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), <span class="number">1</span>, <span class="number">0</span>);</span><br><span class="line">        ASSERT(res);</span><br><span class="line">        mGone = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></handle></p>
<p>通过mGate对mBlocked保护起来，当唤醒的个数超过指定值会把多余的mblocked去掉并且把<br>虚假唤醒数量置空。举个例子，当mBLocked为1时该线程被虚假唤醒，那么mGone变为1，由于是<br>虚假唤醒，用户在外部调用wait函数时通过while循环判断条件不满足再次进入wait中enterGate<br>函数对mBlocked自增，此时mBlocked数量为2，所以当冗余的mBlocked超过指定值，就回去掉<br>这些mBlocked并将mGone置空。<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (wasWaiting == <span class="number">1</span>)</span><br><span class="line">&#123;</span><br><span class="line">   <span class="keyword">for</span> (; wasGone; --wasGone)</span><br><span class="line">   &#123;</span><br><span class="line">    res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mQueue), INFINITE);</span><br><span class="line">    ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">   &#125;</span><br><span class="line">   res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), <span class="number">1</span>, <span class="number">0</span>);</span><br><span class="line">   ASSERT(res);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该函数判断Condation类的mWating变量有1变为0，并且阻塞的线程数为0，因为如果用户没有在外边调用while<br>判断条件导致虚假唤醒引起逻辑错误，所以为了起到保护作用对那些因为虚假唤醒错过的信号进行资源占用，<br>直到信号量都被释放后才进入mGate释放。举一个例子如果外部调用<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Lock(mutex);</span><br><span class="line"><span class="keyword">if</span>(条件不满足)</span><br><span class="line">&#123;</span><br><span class="line">　　wait(mutex);</span><br><span class="line">　　</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//逻辑处理</span></span><br><span class="line">　　　　...</span><br><span class="line">UnLock(mutex);</span><br></pre></td></tr></table></figure></p>
<p>当wait执行退出后会执行逻辑，而没有while判断条件是否真的满足。所以我们要对信号量进行控制，保证信号量<br>数量正确。并且和mBlocked，mWait,等一致。<br>下面是signal函数最终版本<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span></span><br><span class="line">Condition::signal ()</span><br><span class="line">&#123;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> WIN32</span></span><br><span class="line">    <span class="keyword">int</span> ret = pthread_cond_signal(&amp;mId);</span><br><span class="line">    ASSERT(ret == <span class="number">0</span>);</span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line">    <span class="keyword">unsigned</span> signals = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> res = <span class="number">0</span>;</span><br><span class="line">    res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex), INFINITE);</span><br><span class="line">    ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (mWaiting != <span class="number">0</span>) </span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">if</span> (mBlocked == <span class="number">0</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            res = ReleaseMutex(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex));</span><br><span class="line">            ASSERT(res);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        ++mWaiting;</span><br><span class="line">        --mBlocked;</span><br><span class="line">        signals = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        res = WaitForSingleObject(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), INFINITE);</span><br><span class="line">        ASSERT(res == WAIT_OBJECT_0);</span><br><span class="line">        <span class="keyword">if</span> (mBlocked &gt; mGone)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span> (mGone != <span class="number">0</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                mBlocked -= mGone;</span><br><span class="line">                mGone = <span class="number">0</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            signals = mWaiting = <span class="number">1</span>;</span><br><span class="line">            --mBlocked;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">        &#123;</span><br><span class="line">            res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mGate), <span class="number">1</span>, <span class="number">0</span>);</span><br><span class="line">            ASSERT(res);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    res = ReleaseMutex(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mMutex));</span><br><span class="line">    ASSERT(res);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (signals)</span><br><span class="line">    &#123;</span><br><span class="line">        res = ReleaseSemaphore(<span class="keyword">reinterpret_cast</span>&lt;HANDLE&gt;(mQueue), signals, <span class="number">0</span>);</span><br><span class="line">        ASSERT(res);</span><br><span class="line">    &#125;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>同样的道理<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (mBlocked &gt; mGone)</span><br><span class="line"> &#123;</span><br><span class="line">    <span class="keyword">if</span> (mGone != <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">         mBlocked -= mGone;</span><br><span class="line">         mGone = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    signals = mWaiting = <span class="number">1</span>;</span><br><span class="line">    --mBlocked;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个逻辑就是处理当虚假唤醒的mBlocked和mGone等数据准确性。因为如果是虚假唤醒，用户通过while(条件不满足)这个方式继续调用wait会导致mBlocked++，假设就一个线程处于阻塞并且因为虚假唤醒通过while循环重新调用wait函数，而此时mGone比mBlocked小1，所以mBlocked - mGone就是更新差值给mBlocked，这是真正的处于阻塞的线程数量。  </p>
<p>下面是代码下载地址：<br><a href="http://download.csdn.net/detail/secondtonone1/9658645" target="_blank" rel="noopener">betternet</a>  </p>
<p>代码效果测试截图：<br><img src="winsignal/1.png" alt="1.png"></p>
<p><img src="winsignal/2.png" alt="2.png"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/C/" rel="tag"># C++</a>
          
            <a href="/tags/Windows环境编程/" rel="tag"># Windows环境编程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/03/cppvirtual/" rel="next" title="C++类成员空间分配和虚函数表">
                <i class="fa fa-chevron-left"></i> C++类成员空间分配和虚函数表
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/03/winsemphore/" rel="prev" title="windows环境利用semophore机制进行线程同步">
                windows环境利用semophore机制进行线程同步 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">恋恋风辰</p>
              <p class="site-description motion-element" itemprop="description">重剑无锋，大巧不工</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">146</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/secondtonone1" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wang-wu-chen-32/activities" target="_blank" title="ZhiHu">
                    
                      <i class="fa fa-fw fa-ZhiHu"></i>ZhiHu</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">恋恋风辰</span>

  
  
 
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
 
 
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.3</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
